package leetcode;

/**
 * Created by Ghost on 2014/12/21.
 */
public class FindNixu {
    private int Rst = 0;

    private int[] partitionAndMerge(int[] num) {
        if (num.length > 1) {
            int aLen = num.length >> 1;
            int[] a = new int[aLen];
            int[] b = new int[num.length - aLen];

            for (int i = 0; i < num.length; i++) {
                if (i < aLen) {
                    a[i] = num[i];
                } else {
                    b[i - aLen] = num[i];
                }
            }
            int[] aa = partitionAndMerge(a);
            int[] bb = partitionAndMerge(b);
            int aIdx = aa.length - 1, bIdx = bb.length - 1;
            int nIdx = num.length - 1;
            while (nIdx >= 0) {
                if (aIdx >= 0 && bIdx >= 0) {
                    if (aa[aIdx] > bb[bIdx]) {
                        Rst+=bIdx+1;
                        num[nIdx] = aa[aIdx];
                        nIdx--;
                        aIdx--;
                    } else if (aa[aIdx] < bb[bIdx]) {
                        num[nIdx] = bb[bIdx];
                        bIdx--;
                        nIdx--;
                    } else {
                        num[nIdx] = aa[aIdx];
                        aIdx--;
                        nIdx--;
                        num[nIdx] = bb[bIdx];
                        bIdx--;
                        nIdx--;
                    }
                }
                else if(aIdx>=0 && bIdx<0){
                    for(;nIdx>=0 && aIdx>=0;nIdx--,aIdx--){
                        num[nIdx] = aa[aIdx];
                    }
                }else{
                    for(;nIdx>=0 && bIdx>=0;nIdx--,bIdx--)
                        num[nIdx] = bb[bIdx];
                }
            }
            return num;
        } else {
            return num;
        }
    }

    public int findNixu(int[] num) {
        if(num.length<=0)
            return 0;
        partitionAndMerge(num);
        return Rst;
    }

    public static void main(String[] args) {
        FindNixu findNixu = new FindNixu();
        int[] num = {5,4,3,2,1};
        System.out.println(findNixu.findNixu(num));
    }
}
